package com.example.medicalapp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.medicalapp.R;
import com.example.medicalapp.activity.WelcomeActivity;
import com.example.medicalapp.helper.DatabaseHelper;
import com.example.medicalapp.model.User;
import com.example.medicalapp.util.PreferencesUtil;

public class LoginFragment extends Fragment {
    private static final String TAG = "LoginFragment";
    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    private boolean isDoctor;
    private DatabaseHelper dbHelper;
    private PreferencesUtil preferencesUtil;

    // 创建Fragment实例的静态方法
    public static LoginFragment newInstance(boolean isDoctor) {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        args.putBoolean("is_doctor", isDoctor);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            isDoctor = getArguments().getBoolean("is_doctor");
        }
        Log.d(TAG, "onCreate: isDoctor=" + isDoctor);

        // 初始化数据库帮助类和SharedPreferences工具类
        if (getActivity() != null) {
            dbHelper = new DatabaseHelper(getActivity());
            preferencesUtil = new PreferencesUtil(getActivity());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //  Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);

        // 初始化视图
        initViews(view);

        // 设置点击监听器
        setupListeners();

        return view;
    }

    private void initViews(View view) {
        etUsername = view.findViewById(R.id.et_username);
        etPassword = view.findViewById(R.id.et_password);
        btnLogin = view.findViewById(R.id.btn_login);
        Log.d(TAG, "Views initialized");
    }

    private void setupListeners() {
        btnLogin.setOnClickListener(v -> attemptLogin());
    }

    private void attemptLogin() {
        // 获取输入内容
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 基本验证
        if (username.isEmpty()) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        Log.d(TAG, "Attempting login with username: " + username);

        // 调用数据库方法验证用户
        User user = dbHelper.checkUser(username, password);

        if (user != null) {
            // 验证角色是否匹配
            if ((isDoctor && "doctor".equals(user.getRole())) ||
                    (!isDoctor && "patient".equals(user.getRole()))) {

                // 登录成功，保存登录状态
                preferencesUtil.saveLoginStatus(user);
                Log.d(TAG, "Login successful for user: " + username + ", role: " + user.getRole());

                // 跳转到欢迎页面
                Intent intent = new Intent(getActivity(), WelcomeActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);

                if (getActivity() != null) {
                    getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                }
            } else {
                // 角色不匹配
                String message = isDoctor ? "该账号不是医生账号" : "该账号不是患者账号";
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Login failed: role mismatch");
            }
        } else {
            // 登录失败
            Toast.makeText(getActivity(), "用户名或密码错误", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Login failed: invalid credentials");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
